var Q = require('q');
var AV = require('leanengine');
var async = require('async');
var Product = AV.Object.extend("Product");
var demoData = [
    {
        id: 1,
        title: 'Test A', name: '（会员专享）【新疆直供】库尔勒香梨',
        intro: '酥脆细嫩 浓甜无渣',
        inventory: 999,
        content: '<img src="http://7xj380.com1.z0.glb.clouddn.com/2015-10-13_561cd8da98085.jpg" alt="" /><img src="http://7xj380.com1.z0.glb.clouddn.com/2015-10-13_561cd91eb53e4.jpg" alt="" /><img src="http://7xj380.com1.z0.glb.clouddn.com/2015-10-13_561cd923e0196.jpg" alt="" /><img src="http://7xj380.com1.z0.glb.clouddn.com/2015-10-13_561cd92541f57.jpg" alt="" /><img src="http://7xj380.com1.z0.glb.clouddn.com/2015-10-13_561cd9278d800.jpg" alt="" /><img src="http://7xj380.com1.z0.glb.clouddn.com/2015-10-13_561cd929d42d5.jpg" alt="" /><img src="http://7xj380.com1.z0.glb.clouddn.com/2015-10-13_561cd92aceb4a.jpg" alt="" /><img src="http://7xj380.com1.z0.glb.clouddn.com/2015-10-13_561cd92e83890.jpg" alt="" />',
        price: 12,
        picurlarray: '["http:\/\/7xj380.com1.z0.glb.clouddn.com\/2015-12-05_566280841c5cb.jpg","http:\/\/7xj380.com1.z0.glb.clouddn.com\/2015-12-05_5662808b23acc.jpg","http:\/\/7xj380.com1.z0.glb.clouddn.com\/2015-12-05_566280909ca6c.jpg"]',
        spec:{
            "22":{id:"20011",grprice:"25.00",name:'5件',point:5},
            "23":{id:"20012",grprice:"31.00",name:'2件',point:2},
            "25":{id:"20013",grprice:"35.00",name:'1件',point:1}
        }
    }
];

function parseObject(o){
    //获取产品的阶梯价格

    var picurlarray = eval(o.picurlarray);
    o.picurlarray = picurlarray;


    var specs = o.spec;
    var list = [];

    for(var k in specs){
        list.push(specs[k]);
    }

    list = list.sort(function(a,b){
        var pa = parseFloat(a.grprice);
        var pb = parseFloat(b.grprice);
        return pb - pa;
    });

    o.prices = list;
    o.min = list[list.length-1];
    o.max = list[0];

    return o;
}

module.exports = {
    /**
     * 获取产品列表
     */
    list:function(){
        var deferred = Q.defer();

        deferred.resolve(demoData);

        return deferred.promise;
    },
    get:function(id){
        var deferred = Q.defer();
        //var o = demoData[0];
        console.log(id);
        var query = new AV.Query(Product);
        query.get(id).then(function(data){
            var o = data.toJSON();
            o = parseObject(o);
            deferred.resolve(o);
        }).catch(function(err){
            //deferred.resolve(o);
            console.log(err);
        });

        return deferred.promise;
    }

}